import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { Row, Col, message, Form, Spin } from "antd";
import { ListView, Card, Modal, DatePicker, List, Button, SearchBar, InputItem, Toast, WhiteSpace } from "antd-mobile";
import './index.less';
import { request, setMainFormTitle } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";

// const Item = List.Item;

function MyBody(props: any) {
    return (
        <div className="am-list-body my-body" style={{ height: '100%' }}>
            {props.children}
        </div>
    );
}
/**
 * 组件：活动室列表视图控件状态
 */
export interface ActivityRoomListViewState extends ReactViewState {

    /** 长列表数据 */
    dataSource?: any;
    /** 请求的数据 */
    list?: any[];
    /** 上拉加载 */
    upLoading?: boolean;
    /** 下拉刷新 */
    pullLoading?: boolean;
    /** 长列表容器高度 */
    height?: any;
    /** 当前第几页 */
    page?: number;
    /** 记录tab状态 */
    tab_status?: string;
    /** 是否显示提示框 */
    is_modal?: boolean;
    /** 操作的活动室 */
    select_room_info?: any;
    /** 预约时间 */
    reservate_date?: any;
    contacts?: any;
    reservate_quantity?: any;
    phone?: any;

    empty?: any;
    animating?: any;
    pageCount?: number;

    // 搜索关键字
    keyword?: string;
}
/**
 * 组件：活动室列表视图控件
 */
export class ActivityRoomListView extends ReactView<ActivityRoomListViewControl, ActivityRoomListViewState> {
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            dataSource: ds,
            list: [],
            upLoading: false,
            pullLoading: false,
            height: document.documentElement!.clientHeight,
            page: 1,
            tab_status: 'enroll',
            is_modal: false,
            contacts: '',
            reservate_quantity: '',
            phone: '',
            empty: false,
            animating: true,
            pageCount: 10,
            keyword: '',
        };
    }
    componentDidMount() {
        this.getActivityRoomList({});
    }
    getActivityRoomList(extra: any = {}, newPage: number = 1) {
        let { list, pageCount } = this.state;
        let param: any = { ...extra };
        this.setState(
            {
                animating: true,
            },
            () => {
                request(this, AppServiceUtility.activity_service.get_activity_room_list_all!(param, newPage, pageCount))
                    .then((data: any) => {
                        if (data && data.result.length > 0) {
                            this.setState({
                                list: list!.concat(data.result),
                                page: newPage,
                                animating: false,
                            });
                        } else {
                            this.setState({
                                animating: false,
                                empty: true,
                            });
                        }
                    }).catch((err) => {
                        console.info(err);
                    });
            }
        );
    }
    // /** 明细点击事件 */
    // on_click_detail = (id: string) => {
    //     this.props.history!.push(ROUTE_PATH.activityDetail + '/' + id + '/' + this.state.tab_status);
    // }
    // /** tab切换触发事件 */
    // tab_click = (tab: any, index: number) => {
    //     let tab_status = 'other';
    //     switch (index) {
    //         case 0:
    //             tab_status = 'enroll';
    //             break;
    //         case 1:
    //             tab_status = 'progress';
    //             break;
    //         case 2:
    //             tab_status = 'finish';
    //             break;
    //         default:
    //             tab_status = 'other';
    //             break;
    //     }
    //     this.setState({ tab_status: tab_status, page: 1 });
    //     request(this, AppServiceUtility.activity_service.get_activity_list!({ 'status': tab_status }, 1, 10))
    //         .then((data: any) => {
    //             console.log('datas.result', data.result);
    //             this.setState({
    //                 list: data.result,
    //             });
    //         });
    // }
    /** 下拉事件 */
    onEndReached = () => {
        const { animating, page } = this.state;
        if (animating === true) {
            return;
        }
        this.getActivityRoomList({}, page! + 1);
    }
    reservateActivityRoom = (owData: any) => {
        this.setState({
            is_modal: true,
            select_room_info: owData,
        });
    }
    format(date: any) {
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
    on_btn_submit = () => {
        const { select_room_info, contacts, phone, reservate_quantity, reservate_date } = this.state;
        if (!select_room_info) {
            Toast.fail('请刷新页面！');
            return;
        }
        if (!reservate_date) {
            Toast.fail('请选择预约日期！');
            return;
        }
        if (!contacts) {
            Toast.fail('请输入联系人！');
            return;
        }
        if (!phone) {
            Toast.fail('请输入联系号码！');
            return;
        }
        if (!(/^1[3456789]\d{9}$/.test(phone))) {
            Toast.fail('请输入正确的联系号码！');
            return;
        }
        if (!reservate_quantity) {
            Toast.fail('请输入预约人数！');
            return;
        }
        // 非0正整数
        if (!(/^\+?[1-9][0-9]*$/.test(reservate_quantity))) {
            Toast.fail('请输入正确的预约人数！');
            return;
        }
        if (reservate_quantity > select_room_info['max_quantity']) {
            Toast.fail('预约人数大于活动室最大可预约人数！');
            return;
        }
        let param: any = {
            reservate_room_id: select_room_info.id,
            contacts,
            phone,
            reservate_quantity: Number(reservate_quantity),
            reservate_date: reservate_date,
            reservate_datestr: this.format(reservate_date),
        };
        request(this, AppServiceUtility.activity_service.update_activity_room_reservation!(param))
            .then((data: any) => {
                if (data === 'Success') {
                    Toast.success('预约成功', 3, () => {
                        window.location.reload();
                    });
                } else {
                    Toast.fail(data);
                }
                this.setState({
                    is_modal: false
                });
            }).catch((error: Error) => {
                message.error(error.message);
                this.setState({
                    is_modal: false
                });
            });
    }
    onClose = () => {
        this.setState({
            is_modal: false
        });
    }
    searchKey(e: any) {
        this.setState(
            {
                empty: false,
                keyword: e,
                list: [],
            },
            () => {
                this.getActivityRoomList({ activity_room_name: e });
            }
        );
    }
    getTag(data: any) {
        const spanWidth = 7;
        const style = {
            borderRadius: '5px',
            color: '#fff',
            padding: '2px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
        };
        if (data.hasOwnProperty('is_reservate')) {
            if (data['is_reservate'] > 0) {
                return (
                    <Col span={spanWidth} style={{ background: "#ed7d31", ...style }}>已占用</Col>
                );
            } else {
                return (
                    <Col span={spanWidth} style={{ background: "#70ad47", ...style }}>空闲中</Col>
                );
            }
        }
        return (
            <Col span={spanWidth} />
        );
    }
    changeValue = (e: any, inputName: any) => {
        this.setState({
            [inputName]: e
        });
    }
    render() {
        setMainFormTitle('活动室管理');
        const { list, dataSource, animating, empty } = this.state;
        // 获取item进行展示
        const renderRow = (owData: any, sectionID: any, rowID: any) => {
            return (
                <Card className='list-conten' >
                    {/* <SwipeAction
                        key={rowID}
                        autoClose={true}
                        right={[
                            {
                                text: '预约',
                                onPress: () => this.reservateActivityRoom(owData),
                                style: { backgroundColor: '#F4333C', color: 'white' },
                            }
                        ]}
                    > */}
                    <Row type='flex' justify='center'>
                        <Col className='list-col' span={10}><img src={owData.photo} style={{ width: '100pt', height: '72pt' }} /></Col>
                        <Col span={14} className='list-col'>
                            <Row>
                                <Col span={17}><strong>{owData.activity_room_name}</strong></Col>
                                {this.getTag(owData)}
                            </Row>
                            <Row className='list-row'>所属机构：{owData.organization_name}</Row>
                            {owData.begin_date && owData.end_date ? <Row className='list-row'>开放时间：{owData.begin_date} - {owData.end_date}</Row> : null}
                            {owData.hasOwnProperty('after_reservate') && owData['after_reservate'].length > 0 ? <Row>
                                <Row className='list-row'>
                                    <Col span={10}>预约列表：</Col>
                                    <Col span={14}>
                                        {owData['after_reservate'].map((item: any, index: number) => {
                                            return (
                                                <Row key={index}>{item.reservate_datestr}</Row>
                                            );
                                        })}
                                    </Col>
                                </Row>
                            </Row> : null}
                            <Row className='list-row'>地址：{owData.address}</Row>
                            <Row className='list-row'>可容纳人数：{owData.max_quantity}</Row>
                            {/* <Row>
                                    <Col span={16}>已经报名：{owData.acount} / {owData.max_quantity}</Col>
                                    <Col span={8}><a className='list-a'>{owData.amount === 0 ? '免费' : owData.amount}</a></Col>
                                </Row> */}
                        </Col>
                    </Row>
                    {/* </SwipeAction> */}
                </Card>
            );
        };
        return (
            <Row>
                <SearchBar placeholder="搜索" maxLength={8} onSubmit={(e: any) => this.searchKey(e)} />
                <Modal
                    popup={true}
                    visible={this.state.is_modal!}
                    onClose={this.onClose}
                    animationType="slide-up"
                    className="defaultModal"
                >
                    <Card>
                        <Card.Header title='预约信息' />
                        <Card.Body>
                            <List>
                                <DatePicker
                                    mode="date"
                                    extra="请选择预约日期"
                                    value={this.state.reservate_date}
                                    onChange={reservate_date => this.setState({ reservate_date })}
                                    format={'YYYY-MM-DD'}
                                >
                                    <List.Item arrow="horizontal">预约日期</List.Item>
                                </DatePicker>
                            </List>
                            <List renderHeader={() => '联系人'}>
                                <InputItem placeholder="请输入联系人" onChange={(e) => this.changeValue(e, 'contacts')} />
                            </List>
                            <List renderHeader={() => '预约人数'}>
                                <InputItem placeholder="请输入预约人数" onChange={(e) => this.changeValue(e, 'reservate_quantity')} />
                            </List>
                            <List renderHeader={() => '联系电话'}>
                                <InputItem placeholder="请输入联系电话" onChange={(e) => this.changeValue(e, 'phone')} />
                            </List>
                            <Button type='primary' onClick={this.on_btn_submit}>确定</Button>
                        </Card.Body>
                    </Card>
                </Modal>
                <Row className='tabs-content'>
                    {
                        list && list.length ?
                            <ListView
                                ref={el => this['lv'] = el}
                                dataSource={dataSource.cloneWithRows(list)}
                                renderRow={renderRow}
                                initialListSize={10}
                                pageSize={10}
                                renderBodyComponent={() => <MyBody />}
                                style={{ height: this.state.height }}
                                onEndReached={this.onEndReached}
                            /> : null
                    }
                    {animating ? <Row>
                        <WhiteSpace size="lg" />
                        <Row style={{ textAlign: 'center' }}>
                            <Spin size="large" />
                        </Row>
                        <WhiteSpace size="lg" />
                    </Row> : null}
                    {empty ? <Row>
                        <WhiteSpace size="lg" />
                        <Row className='tabs-content' type='flex' justify='center'>{list && list.length ? '已经是最后一条了' : '无数据'}</Row>
                        <WhiteSpace size="lg" />
                    </Row> : null}
                </Row>
            </Row>
        );
    }
}

/**
 * 组件：活动室列表视图控件
 * 控制活动室列表视图控件
 */
@addon('ActivityRoomListView', '活动室列表视图控件', '控制活动室列表视图控件')
@reactControl(Form.create<any>()(ActivityRoomListView), true)
export class ActivityRoomListViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}